﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Net.WebSockets;
using System.Threading.Tasks;
using Tiens.NotificationHub.Services;
using Tiens.NotificationHub.Constant;

namespace Tiens.NotificationHub.Core
{
    public class NotificationsHub : Hub
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IAppConnectionManager _appConnectionManager;

        public NotificationsHub(IHttpContextAccessor httpContextAccessor, IAppConnectionManager appConnectionManager)
        {
            _httpContextAccessor = httpContextAccessor;
            _appConnectionManager = appConnectionManager;
        }

        public override async Task OnConnectedAsync()
        {
            var appId = _httpContextAccessor.HttpContext.Request.Query["appId"];
            ValidateAppIdQueryString(appId);

            await Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name.ToGroupName(appId));

            await _appConnectionManager.JoinAsync(Context.User.Identity.Name, appId, Context.ConnectionId);
            await base.OnConnectedAsync();
        }


        public override async Task OnDisconnectedAsync(Exception ex)
        {
            var appId = _httpContextAccessor.HttpContext.Request.Query["appId"];
            ValidateAppIdQueryString(appId);

            var groupName = Context.User.Identity.Name.ToGroupName(appId);
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);

            await _appConnectionManager.QuitAsync(groupName, appId, Context.ConnectionId);
            await base.OnDisconnectedAsync(ex);
        }


        void ValidateAppIdQueryString(string appId)
        {
            if (string.IsNullOrWhiteSpace(appId))
                throw new WebSocketException("没有配置 appId");
        }
    }


}
